home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C24 / Reinterp.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.1 KB  |  47 lines

  1. //: C24:Reinterp.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Reinterpret_cast
  7. // Example depends on VPTR location,
  8. // Which may differ between compilers.
  9. #include <cstring>
  10. #include <fstream>
  11. using namespace std;
  12. ofstream out("reinterp.out");
  13.  
  14. class X {
  15.   static const int sz = 5 ;
  16.   int a[sz];
  17. public:
  18.   X() { memset(a, 0, sz * sizeof(int)); }
  19.   virtual void f() {}
  20.   // Size of all the data members:
  21.   int membsize() { return sizeof(a); }
  22.   friend ostream&
  23.     operator<<(ostream& os, const X& x) {
  24.       for(int i = 0; i < sz; i++)
  25.         os << x.a[i] << ' ';
  26.       return os;
  27.   }
  28.   virtual ~X() {}
  29. };
  30.  
  31. int main() {
  32.   X x;
  33.   out << x << endl; // Initialized to zeroes
  34.   int* xp = reinterpret_cast<int*>(&x);
  35.   xp[1] = 47;
  36.   out << x << endl; // Oops!
  37.  
  38.   X x2;
  39.   const int vptr_size= sizeof(X) - x2.membsize();
  40.   long l = reinterpret_cast<long>(&x2);
  41.   // *IF* the VPTR is first in the object:
  42.   l += vptr_size; // Move past VPTR
  43.   xp = reinterpret_cast<int*>(l);
  44.   xp[1] = 47;
  45.   out << x2 << endl;
  46. } ///:~
  47.